"""
模型管理模块
负责加载、缓存和管理 InsightFace 模型
"""
import os
import sys
from pathlib import Path
from typing import Optional
from insightface.app import FaceAnalysis
from loguru import logger

# 配置日志（简单版本，避免重复配置）
if not logger._core.handlers:
    logger.remove()
    logger.add(
        sys.stderr,
        format="<green>{time:HH:mm:ss}</green> | <level>{level: <8}</level> | <level>{message}</level>",
        level="INFO"
    )

from config import settings


class ModelManager:
    """模型管理器 - 单例模式"""
    
    _instance: Optional['ModelManager'] = None
    _model: Optional[FaceAnalysis] = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        """初始化模型管理器"""
        if self._model is None:
            self._load_model()
    
    def _load_model(self):
        """加载 InsightFace 模型"""
        try:
            logger.info(f"开始加载模型: {settings.model_name}")
            
            # 设置模型路径
            model_path = Path(settings.model_dir)
            model_path.mkdir(parents=True, exist_ok=True)
            
            # 设置环境变量
            os.environ['INSIGHTFACE_HOME'] = str(model_path.absolute())
            
            logger.info(f"模型目录: {model_path.absolute()}")
            
            # 初始化 FaceAnalysis
            self._model = FaceAnalysis(
                name=settings.model_name,
                root=str(model_path.absolute()),
                providers=['CPUExecutionProvider']  # 使用CPU，如需GPU改为CUDAExecutionProvider
            )
            
            # 准备模型
            logger.info("准备模型...")
            self._model.prepare(
                ctx_id=settings.ctx_id,
                det_size=settings.det_size
            )
            
            logger.info("✅ 模型加载成功")
            
        except Exception as e:
            logger.error(f"❌ 模型加载失败: {e}")
            logger.error(f"请确保模型文件在: {settings.model_dir}/{settings.model_name}/")
            raise
    
    def get_model(self) -> FaceAnalysis:
        """获取模型实例"""
        if self._model is None:
            self._load_model()
        return self._model
    
    def reload_model(self):
        """重新加载模型"""
        logger.info("重新加载模型")
        self._model = None
        self._load_model()
    
    @property
    def is_ready(self) -> bool:
        """检查模型是否就绪"""
        return self._model is not None
    
    def get_model_info(self) -> dict:
        """获取模型信息"""
        return {
            "model_name": settings.model_name,
            "model_dir": settings.model_dir,
            "is_ready": self.is_ready,
            "ctx_id": settings.ctx_id,
            "det_size": settings.det_size
        }


# 创建全局模型管理器实例
model_manager = ModelManager()

